<template>
  <div class="create-post-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="top" label-width="100px" class="article-form">
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="postForm.title" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6" :offset="3">
          <el-form-item label="所属群组" prop="clusterId">
            <el-select
              v-model="postForm.clusterId"
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in clusterOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属分类" prop="field">
            <el-select
              v-model="postForm.field"
              multiple
              filterable
              placeholder="可多选"
              style="width:100%"
            >
              <el-option
                v-for="item in fieldOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6" :offset="3">
          <el-form-item label="作者" prop="author">
            <el-input v-model="postForm.author" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标签" prop="label">
            <el-select
              v-model="postForm.label"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="可自行输入，并按下回车选择标签"
              style="width:100%"
            >
              <el-option
                v-for="(item, index) in postForm.label"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="CODE" prop="code">
            <el-input v-model="postForm.code" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="相关会议" prop="meeting">
            <el-select
              v-model="postForm.meeting"
              multiple
              filterable
              placeholder="在关联会议的“会后报道”页面显示该文章"
              style="width:100%"
            >
              <el-option
                v-for="item in meetingOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="外部链接" prop="link">
            <el-input v-model="postForm.link" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="用户权限" prop="power">
            <el-select
              v-model="postForm.power"
              multiple
              placeholder="可多选，不选择则不可查看"
              style="width:100%"
            >
              <el-option
                v-for="item in powerOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="相关产品" prop="brandids">
            <el-select
              v-model="postForm.brandids"
              multiple
              filterable
              placeholder="可多选"
              style="width:100%"
            >
              <el-option
                v-for="item in productsOptions"
                :key="item.id"
                :label="item.brand"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6" :offset="3">
          <el-form-item label="发布日期" prop="publishtime">
            <el-date-picker
              v-model="postForm.publishtime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              style="width:100%"
              :picker-options="publishTimeOptions"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="结束日期" prop="expiretime">
            <el-date-picker
              v-model="postForm.expiretime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              style="width:100%"
              :picker-options="expireTimeOptions"
            />
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item label="是否上线" prop="state" class="text-center">
            <el-switch v-model="postForm.state" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item label="可分享" prop="share" class="text-center">
            <el-switch v-model="postForm.share" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item label="HT" prop="ht" class="text-center">
            <el-switch v-model="postForm.ht" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="上传封面" prop="cover">
            <el-upload
              v-if="coverList.length < 1"
              :action="uploadUrl"
              :multiple="false"
              :limit="1"
              name="fies"
              :headers="{token}"
              :on-success="handleUploadSucc"
              :show-file-list="false"
              drag
              accept="image/jpeg,image/png,image/gif"
              class="drag-upload-wrapper"
            >
              <i class="el-icon-upload" />
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>

            <ul v-else class="thumb-img-list">
              <li
                v-for="(item, index) in coverList"
                :key="index"
                class="item"
              >
                <img :src="item.url" :alt="item.name" class="img">
                <div
                  class="el-icon-close close-btn"
                  title="点击可删除"
                  @click="handleUploadRemove(item)"
                />
              </li>
            </ul>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="文章描述" prop="notes">
            <el-input v-model="postForm.notes" type="textarea" rows="4" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="内容" prop="content">
            <vue-ueditor-wrap
              v-model="postForm.content"
              :config="ueditorConfig"
              :destroy="true"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="mt30">
        <el-col :span="18" :offset="3">
          <el-form-item>
            <el-button type="primary" @click="submitForm">提 交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import VueUeditorWrap from 'vue-ueditor-wrap'
import { mapGetters } from 'vuex'
import {
  getCategories,
  getArticleShow,
  updateArticle,
  addArticle
} from '@/api/articles'
import {
  getUserState,
  getBrands,
  getAllCluster
} from '@/api/baseData'

const defaultForm = {
  id: undefined,
  title: '',
  clusterId: '',
  field: [],
  author: '',
  label: [],
  meeting: [],
  link: '',
  code: '',
  publishtime: '',
  expiretime: '',
  power: [],
  brandids: [],
  cover: '',
  notes: '',
  content: '',
  state: 0,
  share: 0,
  ht: 0
}

export default {
  name: 'ArticleForm',
  components: {
    VueUeditorWrap
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const self = this
    return {
      clusterOptions: [],
      fieldOptions: [],
      meetingOptions: [],
      powerOptions: [],
      productsOptions: [],
      coverList: [],
      postForm: Object.assign({}, defaultForm),
      expireTimeOptions: {
        disabledDate(time) {
          return self.$moment(self.postForm.publishtime).isAfter(time.getTime())
        }
      },
      publishTimeOptions: {
        disabledDate(time) {
          return self.$moment(self.postForm.expiretime).isBefore(time.getTime())
        }
      },
      loading: false,
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字', trigger: 'blur' }
        ],
        clusterId: [
          { required: true, message: '请选择所属群组', trigger: 'change' }
        ],
        field: [
          { required: true, message: '请选择所属分类', trigger: 'change' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字', trigger: 'blur' }
        ],
        // link: [
        //   { required: true, message: '请输入外部链接', trigger: 'blur' }
        // ],
        // code: [
        //   { required: true, message: '请输入CODE', trigger: 'blur' }
        // ],
        // publishtime: [
        //   { required: true, message: '请选择发布时间', trigger: 'change' }
        // ],
        power: [
          { required: true, message: '请选择用户权限', trigger: 'change' }
        ],
        cover: [
          { required: true, message: '请上传封面', trigger: 'change' }
        ],
        // notes: [
        //   { required: true, message: '请输入文章描述' }
        // ],
        content: [
          { required: true, message: '请输入内容' }
        ]
      },
      ueditorConfig: {
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 初始容器高度
        initialFrameHeight: 1000,
        // 初始容器宽度
        initialFrameWidth: '100%',
        // 上传文件接口
        serverUrl: process.env.VUE_APP_BASE_API + '/config',
        // UEditor 资源文件的存放路径，vuecli2放在static目录无需配置以下，vuecli3放在public目录，需配置
        UEDITOR_HOME_URL: '/UEditor/'
      },
      uploadUrl: process.env.VUE_APP_BASE_API + '/content/imgUpload'
    }
  },
  computed: {
    ...mapGetters([
      'token'
    ])
  },
  created() {
    this.fetchClusterList()
    this.fetchFieldList()
    this.fetchUserState()
    this.fetchtProducts()
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }
  },
  methods: {
    fetchClusterList() {
      getAllCluster().then(response => {
        // console.log(response)
        this.clusterOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchFieldList() {
      getCategories().then(response => {
        // console.log(response)
        this.fieldOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchUserState() {
      getUserState().then(response => {
        this.powerOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchtProducts() {
      getBrands().then(response => {
        // console.log(response)
        this.productsOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    // clusterChange(data) {
    //   // console.log(data);
    //   getCategories({ clusterId: data }).then(response => {
    //     // console.log(response)
    //     console.log(response.data.length)
    //     this.fieldOptions = []
    //     this.fieldOptions = response.data
    //   }).catch(err => {
    //     console.log(err)
    //   })
    // },
    fetchData(id) {
      getArticleShow({ id }).then(response => {
        const { data } = response
        // console.log(data)
        // data.imgs.forEach((item, index) => {
        //   this.coverList.push({
        //     name: 'uploadCover' + index,
        //     url: item
        //   })
        // })
        this.coverList = []
        this.coverList.push({
          name: 'uploadCover' + 0,
          url: data.imgs[0]
        })
        this.postForm.id = data.id
        this.postForm.title = data.title
        this.postForm.clusterId = data.clusterId
        this.postForm.field = data.field
        this.postForm.author = data.author
        this.postForm.label = data.label
        this.postForm.meeting = data.meeting
        this.postForm.link = data.link
        this.postForm.code = data.code
        this.postForm.publishtime = data.publishtime
        this.postForm.expiretime = data.expiretime
        this.postForm.power = data.power
        this.postForm.brandids = data.brandidList
        this.postForm.state = data.state
        this.postForm.share = data.share
        this.postForm.ht = data.ht
        this.postForm.cover = data.imgs[0]
        this.postForm.notes = data.notes
        this.postForm.content = data.content
        console.log(this.coverList)
      }).catch(err => {
        console.log(err)
      })
    },
    handleUploadRemove(file) {
      // console.log(file)
      const index = this.coverList.indexOf(file)
      if (index !== -1) {
        this.coverList.splice(index, 1)
        // this.postForm.cover.splice(index, 1)
        this.postForm.cover = ''
      }
      // console.log(this.coverList)
    },
    handleUploadSucc(res) {
      // console.log(res)
      // this.postForm.cover = res.data
      res.data.forEach((item, index) => {
        if (this.coverList.indexOf(item) === -1) {
          // this.postForm.cover.push(item)
          this.postForm.cover = item
          this.coverList.push({
            name: 'uploadCover' + index,
            url: item
          })
        }
      })
      // console.log(this.postForm.cover)
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          // this.postForm.clusterId = this.postForm.clusterId.join(',')
          this.postForm.field = this.postForm.field.join(',')
          this.postForm.label = this.postForm.label.join(',')
          this.postForm.meeting = this.postForm.meeting.join(',')
          this.postForm.power = this.postForm.power.join(',')
          this.postForm.brandids = this.postForm.brandids.join(',')
          // this.postForm.cover = this.postForm.cover.join(',')

          this.loading = true
          if (this.isEdit) {
            updateArticle(this.postForm).then(response => {
              // console.log(response)
              this.$notify({
                title: '成功',
                message: '编辑文章成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.go(-1)
            }).catch(err => {
              console.log(err)
            })
          } else {
            addArticle(this.postForm).then(response => {
              // console.log(response)
              this.$notify({
                title: '成功',
                message: '添加文章成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.go(-1)
            }).catch(err => {
              console.log(err)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.postForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.create-post-container {
  position: relative;
  .article-form {
    padding: 40px;
  }
}
</style>
